package edu.utexas.esel.jgraphpad.archpadplugin.model;

import java.util.HashMap;
import java.util.Map;

import org.jgraph.graph.GraphLayoutCache;

import com.jgraph.pad.JGraphpadDiagram;

import edu.utexas.esel.jgraphpad.archpadplugin.Utils;
import edu.utexas.esel.jgraphpad.archpadplugin.graph.ElementGraphCell;

/**
 * Diagram for ArchPad documents.
 *
 * @author svetoslavganov@mail.utexas.edu
 */
public class ArchPadDiagram extends JGraphpadDiagram {

	private static final long serialVersionUID = 1L;

	private RegionManager mRegionManager;

	/**
	 * Creates a new instance for a given {@link GraphLayoutCache} and with a
	 * given name.
	 *
	 * @param name The name.
	 * @param graphLayoutCache The cache.
	 */
	public ArchPadDiagram(String name, GraphLayoutCache graphLayoutCache) {
		this(name, graphLayoutCache, new HashMap<Object, Object>());
		
	}

	/**
	 * Creates a new instance for a given <code>graphLayoutCache</code> and
	 * with a given <code>name</code> and <code>properties</code>.
	 *
	 * @param name The name.
	 * @param graphLayoutCache The cache.
	 */
	public ArchPadDiagram(String name, GraphLayoutCache graphLayoutCache,
			Map<Object, Object> properties) {
		super(name, graphLayoutCache, properties);
		setRegionManager(new RegionManager());
	}

	/**
	 * Gets the {@link RegionManager} associated with this diagram.
	 *
	 * @return The manager.
	 */
	public RegionManager getRegionManager() {
		return mRegionManager;
	}

	/**
	 * Sets the {@link RegionManager} associated with this diagram.
	 *
	 * @param regionManager The manager.
	 */
	public void setRegionManager(RegionManager regionManager) {
		regionManager.setGraphLayoutCache(graphLayoutCache);
		mRegionManager = regionManager;
	}
	
	/**
	 * Updates the {@link ElementTreeNode#ATTRIBUTE_MEMBERS} of the root
	 * node in the element stored in the cell. This is required since
	 * data is stored separately from meta-data.
	 */
	public void setMembersAttributeInRegionElementRoots() {
		for (ElementGraphCell region : mRegionManager.getRegions()) {
		    StringBuilder builder = new StringBuilder();

		    for (ElementGraphCell member : mRegionManager.getMembers(region)) {
			    builder.append(member.getAttribute(
			    	ElementGraphCell.ATTRIBUTE_ID));
			    builder.append(',');
		    }

		    int length = builder.length();
		    if (length > 0) {
			    builder.delete(length - 1, length);
			    ElementTreeNode root = Utils.getCellElementRoot(region);
			    root.setAttribute(ElementTreeNode.ATTRIBUTE_MEMBERS,
					builder.toString());
		    }
		}
	}
}
